import React, { useState, useEffect } from 'react';
import { Activity, Server, Database, Cpu, HardDrive, Wifi, AlertTriangle, CheckCircle } from 'lucide-react';

interface SystemStatus {
  server: {
    status: 'online' | 'offline';
    uptime: string;
    cpuUsage: number;
    memoryUsage: number;
    diskUsage: number;
  };
  database: {
    status: 'connected' | 'disconnected';
    connections: number;
    responseTime: number;
  };
  services: Array<{
    name: string;
    status: 'running' | 'stopped' | 'error';
    port: number;
  }>;
  alerts: Array<{
    id: string;
    type: 'warning' | 'error' | 'info';
    message: string;
    timestamp: string;
  }>;
}

export const SystemMonitoring: React.FC = () => {
  const [systemStatus, setSystemStatus] = useState<SystemStatus>({
    server: {
      status: 'online',
      uptime: '15天 8小时 32分钟',
      cpuUsage: 35,
      memoryUsage: 68,
      diskUsage: 45
    },
    database: {
      status: 'connected',
      connections: 12,
      responseTime: 45
    },
    services: [
      { name: '访客核验服务', status: 'running', port: 8080 },
      { name: '密钥管理服务', status: 'running', port: 8081 },
      { name: '数据同步服务', status: 'running', port: 8082 },
      { name: '审计日志服务', status: 'error', port: 8083 }
    ],
    alerts: [
      {
        id: 'A001',
        type: 'warning',
        message: '内存使用率超过60%，请关注系统性能',
        timestamp: '2024-12-01 15:30:00'
      },
      {
        id: 'A002',
        type: 'error',
        message: '审计日志服务连接失败，请检查服务状态',
        timestamp: '2024-12-01 14:45:00'
      },
      {
        id: 'A003',
        type: 'info',
        message: '系统备份已完成',
        timestamp: '2024-12-01 12:00:00'
      }
    ]
  });

  // Simulate real-time updates
  useEffect(() => {
    const interval = setInterval(() => {
      setSystemStatus(prev => ({
        ...prev,
        server: {
          ...prev.server,
          cpuUsage: Math.max(20, Math.min(80, prev.server.cpuUsage + (Math.random() - 0.5) * 10)),
          memoryUsage: Math.max(40, Math.min(90, prev.server.memoryUsage + (Math.random() - 0.5) * 5))
        },
        database: {
          ...prev.database,
          responseTime: Math.max(20, Math.min(100, prev.database.responseTime + (Math.random() - 0.5) * 10))
        }
      }));
    }, 3000);

    return () => clearInterval(interval);
  }, []);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'online':
      case 'connected':
      case 'running':
        return 'text-green-600 dark:text-green-400';
      case 'warning':
        return 'text-yellow-600 dark:text-yellow-400';
      case 'offline':
      case 'disconnected':
      case 'stopped':
      case 'error':
        return 'text-red-600 dark:text-red-400';
      default:
        return 'text-gray-600 dark:text-gray-400';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'online':
      case 'connected':
      case 'running':
        return <CheckCircle className="h-5 w-5 text-green-500" />;
      case 'warning':
        return <AlertTriangle className="h-5 w-5 text-yellow-500" />;
      case 'offline':
      case 'disconnected':
      case 'stopped':
      case 'error':
        return <AlertTriangle className="h-5 w-5 text-red-500" />;
      default:
        return <Activity className="h-5 w-5 text-gray-500" />;
    }
  };

  const getAlertColor = (type: string) => {
    switch (type) {
      case 'error':
        return 'bg-red-50 border-red-200 text-red-800 dark:bg-red-900/20 dark:border-red-800 dark:text-red-200';
      case 'warning':
        return 'bg-yellow-50 border-yellow-200 text-yellow-800 dark:bg-yellow-900/20 dark:border-yellow-800 dark:text-yellow-200';
      case 'info':
        return 'bg-blue-50 border-blue-200 text-blue-800 dark:bg-blue-900/20 dark:border-blue-800 dark:text-blue-200';
      default:
        return 'bg-gray-50 border-gray-200 text-gray-800 dark:bg-gray-900/20 dark:border-gray-800 dark:text-gray-200';
    }
  };

  const getUsageColor = (percentage: number) => {
    if (percentage >= 80) return 'bg-red-500';
    if (percentage >= 60) return 'bg-yellow-500';
    return 'bg-green-500';
  };

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white">系统监控</h2>
        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
          实时监控系统运行状态和性能指标
        </p>
      </div>

      {/* System Overview */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Server Status */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center">
              <Server className="h-6 w-6 text-blue-600 dark:text-blue-400 mr-2" />
              <h3 className="text-lg font-medium text-gray-900 dark:text-white">服务器状态</h3>
            </div>
            {getStatusIcon(systemStatus.server.status)}
          </div>
          
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600 dark:text-gray-400">状态</span>
              <span className={`text-sm font-medium ${getStatusColor(systemStatus.server.status)}`}>
                {systemStatus.server.status === 'online' ? '在线' : '离线'}
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600 dark:text-gray-400">运行时间</span>
              <span className="text-sm font-medium text-gray-900 dark:text-white">
                {systemStatus.server.uptime}
              </span>
            </div>
            
            {/* Resource usage */}
            <div className="space-y-2">
              <div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">CPU使用率</span>
                  <span className="text-gray-900 dark:text-white">{systemStatus.server.cpuUsage.toFixed(1)}%</span>
                </div>
                <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                  <div
                    className={`h-2 rounded-full transition-all ${getUsageColor(systemStatus.server.cpuUsage)}`}
                    style={{ width: `${systemStatus.server.cpuUsage}%` }}
                  ></div>
                </div>
              </div>
              
              <div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">内存使用率</span>
                  <span className="text-gray-900 dark:text-white">{systemStatus.server.memoryUsage.toFixed(1)}%</span>
                </div>
                <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                  <div
                    className={`h-2 rounded-full transition-all ${getUsageColor(systemStatus.server.memoryUsage)}`}
                    style={{ width: `${systemStatus.server.memoryUsage}%` }}
                  ></div>
                </div>
              </div>
              
              <div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">磁盘使用率</span>
                  <span className="text-gray-900 dark:text-white">{systemStatus.server.diskUsage}%</span>
                </div>
                <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                  <div
                    className={`h-2 rounded-full ${getUsageColor(systemStatus.server.diskUsage)}`}
                    style={{ width: `${systemStatus.server.diskUsage}%` }}
                  ></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Database Status */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center">
              <Database className="h-6 w-6 text-green-600 dark:text-green-400 mr-2" />
              <h3 className="text-lg font-medium text-gray-900 dark:text-white">数据库状态</h3>
            </div>
            {getStatusIcon(systemStatus.database.status)}
          </div>
          
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600 dark:text-gray-400">连接状态</span>
              <span className={`text-sm font-medium ${getStatusColor(systemStatus.database.status)}`}>
                {systemStatus.database.status === 'connected' ? '已连接' : '未连接'}
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600 dark:text-gray-400">活动连接数</span>
              <span className="text-sm font-medium text-gray-900 dark:text-white">
                {systemStatus.database.connections}
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600 dark:text-gray-400">响应时间</span>
              <span className="text-sm font-medium text-gray-900 dark:text-white">
                {systemStatus.database.responseTime.toFixed(0)}ms
              </span>
            </div>
          </div>
        </div>

        {/* Services Status */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <div className="flex items-center mb-4">
            <Wifi className="h-6 w-6 text-purple-600 dark:text-purple-400 mr-2" />
            <h3 className="text-lg font-medium text-gray-900 dark:text-white">服务状态</h3>
          </div>
          
          <div className="space-y-3">
            {systemStatus.services.map((service, index) => (
              <div key={index} className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">
                    {service.name}
                  </p>
                  <p className="text-xs text-gray-600 dark:text-gray-400">
                    端口: {service.port}
                  </p>
                </div>
                <div className="flex items-center">
                  {getStatusIcon(service.status)}
                  <span className={`ml-1 text-xs ${getStatusColor(service.status)}`}>
                    {service.status === 'running' ? '运行中' : 
                     service.status === 'stopped' ? '已停止' : '错误'}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* System Alerts */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">系统告警</h3>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            系统异常事件和重要通知
          </p>
        </div>

        <div className="p-6">
          {systemStatus.alerts.length === 0 ? (
            <div className="text-center py-8">
              <CheckCircle className="mx-auto h-12 w-12 text-green-400 mb-4" />
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                系统运行正常
              </h3>
              <p className="text-gray-600 dark:text-gray-400">
                当前没有系统告警
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {systemStatus.alerts.map((alert) => (
                <div
                  key={alert.id}
                  className={`border rounded-lg p-4 ${getAlertColor(alert.type)}`}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex">
                      <div className="mr-3 mt-0.5">
                        {alert.type === 'error' && <AlertTriangle className="h-4 w-4" />}
                        {alert.type === 'warning' && <AlertTriangle className="h-4 w-4" />}
                        {alert.type === 'info' && <Activity className="h-4 w-4" />}
                      </div>
                      <div>
                        <p className="text-sm font-medium">
                          {alert.message}
                        </p>
                        <p className="text-xs mt-1 opacity-75">
                          {alert.timestamp}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};